<?php defined('SYSPATH') or die('No direct script access.');
/**
 * 12301合同
 */

class Model_Dispose extends ORM
{
    private static $secretId = 'AKIDekwdCbS7Lb3yqPEaUw5uqVYkagrgoCtMnd32';
    private static $secretKey = 'f0t6chnuCxF7Yjfou5o29L5dqiD88P9pOivkcPzw';
    private static $apiUrl = 'http://api.stccs.com.cn/e12301/api';
    private static $partnerId = '';//测试id：114991817783428586644806444
    private static $status = array(
        array('id' => 1, 'name' => '已生成'),
        array('id' => 2, 'name' => '已签署'),
        array('id' => 3, 'name' => '已作废'),
        array('id' => 4, 'name' => '签署中,部分人员未签署'),// [已签订申请作废]
        array('id' => 5, 'name' => '作废中,部分人员未作废')
    );

    public static function request($data, $type)
    {
        $header = self::generateHeader(self::$apiUrl);
        $rtn = self::http(self::$apiUrl, $data, $header, $type);
        return $rtn;
    }

    /**
     * 生成header
     * @param $uri
     * @return array
     */
    private static function generateHeader($uri)
    {
        date_default_timezone_set('GMT');
        $date = gmdate("D, d M Y H:i:s T");
        date_default_timezone_set('PRC');
        $authorization = self::buildSign($uri, $date);
        $header = array(
            /*  'Host: '.$uri, // 用户 API 所在服务的域名
              'Accept: text/html',*/
            'Uri: ' . $uri,
            'Date: ' . $date,
            'Authorization: ' . $authorization,
            //'X-Requested-With: XMLHttpRequest'
            //'Accept-Encoding: gzip, deflate, sdch'

        );
        return $header;

    }

    private static function http($url, $data, $header, $type = 'post')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $rtn = curl_exec($ch);

        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        }
        curl_close($ch);
        if (self::isJson($rtn)) {
            return json_decode($rtn, true);
        } else {
            return $rtn;
        }
    }

    //判断是否为json
    private static function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }


    private static function validSign()
    {
        //todo sign 验证

        if ($_SERVER['HTTP_AUTHORIZATION'] != self::buildSign($_SERVER['REQUEST_URI'], $_SERVER['HTTP_DATE'])) {
            self::outputError('BA验证错误');
        }
        return true;
    }

    //生成签名
    private static function buildSign($uri, $date)
    {
        $srcStr = "date: " . $date . "\n" . "uri: " . $uri;
        $signStr = base64_encode(hash_hmac('sha1', $srcStr, self::$secretKey, true));
        $authorization = 'hmac id="' . self::$secretId . '", algorithm="hmac-sha1", headers="date uri", signature="';
        $authorization = $authorization . $signStr . "\"";
        return $authorization;


    }

    //上传签章
    public static function uploading_stemp($url, $travelAgencyLicenseNumber)
    {
        //获得12301合同partnerid
        $partnerId = Model_Sysconfig::get_sys_conf('value', 'cfg_contract_partnerid', 0);
        self::$partnerId = $partnerId;
        //获得图片并把图片转为base64
        $supervise['stamp'] = self::fileToBase64(BASEPATH . $url);
        $supervise['uri'] = '/v1/econtract/stamp/' . $travelAgencyLicenseNumber;
        $supervise['partnerId'] = self::$partnerId;
        $result = self::request($supervise, 'post');
        return json_encode($result);
    }

    //将图片进行base64编码
    public static function fileToBase64($image_file)
    {
        $base64_image = '';
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
        $base64 = chunk_split(base64_encode($image_data));
        $base64_image = str_replace("\r\n", "", $base64);
        //$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
        return $base64_image;
    }

    //在线合同申报
    public static function online_reporting_contract($contract_id)
    {
        $constract_supid = $contract_id;
        //获得12301合同partnerid
        $partnerId = Model_Sysconfig::get_sys_conf('value', 'cfg_contract_partnerid', 0);
        self::$partnerId = $partnerId;
        //获得合同信息
        $supervise = DB::select()->from('contract_supervise')->where('id', '=', $constract_supid)->execute()->current();
        if ($supervise) {
            foreach ($supervise as $key => $vel) {
                if (!is_null(json_decode($vel, true))) {
                    $supervise[$key] = json_decode($vel, true);
                }
            }

            unset($supervise['id']);
            unset($supervise['contract_id']);
            unset($supervise['typeid']);
            unset($supervise['contractnName']);
            unset($supervise['addtime']);
            unset($supervise['status']);
            unset($supervise['partyBid']);
            unset($supervise['apiVersion']);
            unset($supervise['fileURL']);
            unset($supervise['signingURL']);
            unset($supervise['QRCodeURL']);

            $supervise['uri'] = '/v1/econtract/apply';
            $supervise['partnerId'] = self::$partnerId;
            $result = self::request($supervise, 'post');
            if ($result['data']) {
                //增加合同编号，文件地址等信息
                if ($result['data']['contractNumber']) {
                    $cdata['contractNumber'] = $result['data']['contractNumber'];
                }
                if ($result['apiVersion']) {
                    $cdata['apiVersion'] = $result['apiVersion'];
                }
                if ($result['data']['fileURL']) {
                    $cdata['fileURL'] = $result['data']['fileURL'];
                }
                if ($result['data']['signingURL']) {
                    $cdata['signingURL'] = $result['data']['signingURL'];
                }
                if ($result['data']['QRCodeURL']) {
                    $cdata['QRCodeURL'] = $result['data']['QRCodeURL'];
                }
                if ($result['data']['viewURL']) {
                    $cdata['viewURL'] = $result['data']['viewURL'];
                }
                $cdata['status'] = 1;
                DB::update('contract_supervise')->set($cdata)->where('id', '=', $constract_supid)->execute();
                //return 'ok';
                return json_encode($result);
            } else {
                return 'no';
            }
        } else {
            return 'no';
        }
    }

}